package cn.water.rocketmq.common;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class CommonConsumer {
    @Test
    public void receiverConsumer() throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
        consumer.setNamesrvAddr("localhost:9876");
        consumer.setConsumerGroup("common-consumer-group");
        consumer.subscribe("common-topic","*");
        MessageListenerConcurrently messageListener = new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt messageExt = list.get(0);
                byte[] body = messageExt.getBody();
                String topic = messageExt.getTopic();
                String keys = messageExt.getKeys();
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println("消费者接收到一条消息:"+message);
                System.out.println("消费者接收到一条消息的主题:"+topic);
                System.out.println("消费者接收到一条消息的keys:"+keys);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        };
        consumer.setMessageListener(messageListener);
        consumer.start();
        while(true);
    }
}
